#!/usr/bin/env node
const express = require('express');
const path = require('path');
const StockService = require('./services/stockService');

// 创建Express应用
const app = express();
const port = 3001; // 使用不同端口避免冲突

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// 模拟股票数据（当数据库不可用时）
const mockStocks = [
  { id: 1, code: '000001', name: '平安银行' },
  { id: 2, code: '600036', name: '招商银行' },
  { id: 3, code: '000858', name: '五粮液' },
  { id: 4, code: '600519', name: '贵州茅台' },
  { id: 5, code: '000002', name: '万科A' }
];

// 存储实时股票数据的缓存
let stockDataCache = new Map();
let lastUpdateTime = null;

// 获取股票数据
async function getStockData() {
  try {
    console.log('正在获取股票数据...');
    const stockCodes = mockStocks.map(stock => {
      let formattedCode = stock.code;
      if (!formattedCode.startsWith('sz') && !formattedCode.startsWith('sh')) {
        if (formattedCode.startsWith('0') || formattedCode.startsWith('3')) {
          formattedCode = 'sz' + formattedCode;
        } else {
          formattedCode = 'sh' + formattedCode;
        }
      }
      return formattedCode;
    });
    
    const stockDataResults = await StockService.updateAllStocks();
    
    // 更新缓存
    stockDataCache.clear();
    stockDataResults.forEach((data, index) => {
      const stock = mockStocks[index];
      stockDataCache.set(stock.id, {
        ...stock,
        ...data,
        timestamp: new Date().toISOString()
      });
    });
    
    lastUpdateTime = new Date();
    console.log(`股票数据更新完成，获取到 ${stockDataResults.length} 只股票数据`);
    return Array.from(stockDataCache.values());
  } catch (error) {
    console.error('获取股票数据失败:', error.message);
    return [];
  }
}

// 路由
app.get('/', async (req, res) => {
  res.render('temp-index', { 
    title: '股票监控系统 (临时版)',
    lastUpdateTime: lastUpdateTime ? lastUpdateTime.toLocaleString('zh-CN') : '未更新'
  });
});

// API: 获取所有股票
app.get('/api/stocks', async (req, res) => {
  try {
    const stocks = Array.from(stockDataCache.values());
    if (stocks.length === 0) {
      // 如果缓存为空，尝试获取数据
      await getStockData();
      const updatedStocks = Array.from(stockDataCache.values());
      res.json(updatedStocks);
    } else {
      res.json(stocks);
    }
  } catch (error) {
    console.error('获取股票列表失败:', error);
    res.status(500).json({ error: '获取股票列表失败' });
  }
});

// API: 获取单个股票价格
app.get('/api/stocks/:id/price', (req, res) => {
  const { id } = req.params;
  const stock = stockDataCache.get(parseInt(id));
  
  if (stock) {
    res.json({
      price: stock.price,
      open_price: stock.openPrice,
      close_price: stock.closePrice,
      high_price: stock.highPrice,
      low_price: stock.lowPrice,
      timestamp: stock.timestamp
    });
  } else {
    res.status(404).json({ error: '未找到股票数据' });
  }
});

// API: 手动更新股票数据
app.post('/api/update', async (req, res) => {
  try {
    const stocks = await getStockData();
    res.json({ 
      message: '股票数据更新成功', 
      count: stocks.length,
      updateTime: lastUpdateTime.toLocaleString('zh-CN')
    });
  } catch (error) {
    console.error('更新股票数据失败:', error);
    res.status(500).json({ error: '更新股票数据失败' });
  }
});

// API: 获取交易时间状态
app.get('/api/trading-status', (req, res) => {
  const isTradingTime = StockService.isTradingTime();
  const nextTradingTime = StockService.getNextTradingTime();
  const now = new Date();
  
  res.json({
    isTradingTime,
    currentTime: now.toLocaleString('zh-CN'),
    nextTradingTime: nextTradingTime.toLocaleString('zh-CN'),
    lastUpdateTime: lastUpdateTime ? lastUpdateTime.toLocaleString('zh-CN') : null
  });
});

// 启动服务器
app.listen(port, async () => {
  console.log('\n🚀 临时股票监控服务器已启动!');
  console.log(`📊 访问地址: http://localhost:${port}`);
  console.log('\n📋 功能说明:');
  console.log('   • 实时股票数据查看');
  console.log('   • 手动数据更新');
  console.log('   • 交易时间状态检查');
  console.log('   • 不依赖数据库运行');
  
  console.log('\n🔧 数据库问题解决后，请使用完整版本:');
  console.log('   node app.js');
  
  // 初始化股票数据
  console.log('\n⏳ 正在初始化股票数据...');
  await getStockData();
  
  // 设置定时更新（仅在交易时间内）
  setInterval(async () => {
    if (StockService.isTradingTime()) {
      console.log('🔄 自动更新股票数据...');
      await getStockData();
    }
  }, 30000); // 30秒更新一次
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n👋 服务器正在关闭...');
  process.exit(0);
});